package member;

import java.io.IOException;
import java.util.Properties;

import javax.mail.AuthenticationFailedException;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import common.TableManager;

@SuppressWarnings("serial")
public class MailSendServlet extends HttpServlet
{
	String address=null;
	String type=null;
	String param=null;
	int id=-1;
	
	String[] params={"rental","reserve"};
	
	RequestDispatcher dispatcher=null;

    protected void doGet(HttpServletRequest request,  HttpServletResponse response) throws ServletException, IOException
    {
        processRequest(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        processRequest(request, response);
    }

	protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
      
       try
        {
    	   type=request.getParameter("type");
    	   System.out.println("LastType:"+type);
        
    	   String strId=(String)request.getParameter("id");
    	   System.out.println("getPara:"+strId);
    	   
    	   if(strId!=null)
    	   {
    		   System.out.println("parse");
    		   id=Integer.parseInt(strId);
    	   }
    	   
	        String from="JA10.project@gmail.com";
	        String to = request.getParameter("userId");
	        String subject =request.getParameter("mailTitle");
	        String message =request.getParameter("mailText");
	        String login = "JA10.project@gmail.com";
	        String password = "createrJA10";
	        
	        Properties props = new Properties();
            props.setProperty("mail.host", "smtp.gmail.com");
            props.setProperty("mail.smtp.port", "587");
            props.setProperty("mail.smtp.auth", "true");
            props.setProperty("mail.smtp.starttls.enable", "true");

            Authenticator auth = new SMTPAuthenticator(login, password);

            Session session = Session.getInstance(props, auth);

            MimeMessage msg = new MimeMessage(session);

            String[] langs = {"ja"};
            msg.setContentLanguage(langs);
            msg.setText(message, "UTF-8");
            msg.setSubject(subject, "UTF-8");
            msg.setFrom(new InternetAddress(from));
            msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            
            //	メール送信
            Transport.send(msg);
            
            address="/member/userMemberSearch.jsp";

           dispatcher = request.getRequestDispatcher(address);
        }
       catch(NullPointerException e)
       {
    	   if(params[0].equals(type))
   			{
    		   address="/member/RentalListServlet";
   			}
    	   else if(params[1].equalsIgnoreCase(type))
    	   {
    		   address="/member/ReserveListServlet";
    	   }
    	   else
    	   {
    		   address="/";
    	   }	
    	   
           dispatcher = request.getRequestDispatcher(address);
       }
       
       catch (AuthenticationFailedException ex)
       {
           request.setAttribute("ErrorMessage", "Authentication failed");
           ex.printStackTrace();
       }
       catch (AddressException ex) 
       {
           request.setAttribute("ErrorMessage", "Wrong email address");
           ex.printStackTrace();
       }
       catch (MessagingException ex) 
       {
           request.setAttribute("ErrorMessage", ex.getMessage());
           ex.printStackTrace();
       }
       finally
       {
    	   if(dispatcher==null)
       		{        		
        		if(params[0].equals(type))
        		{
        			address="/member/userMemberNotreturnMail.jsp";
        		}
        		else if(params[1].equalsIgnoreCase(type))
        		{
        			address="/member/userMemberReserveMail.jsp";
        		}
        		else
        		{
        			address="/";
        		}	
        		dispatcher = request.getRequestDispatcher(address);
        	}
    	   else
    	   {
    		   System.out.println(id);
    		   
    		   if(params[0].equals(type))
    		   {
    			  int count = TableManager.changeMailFlag(TableManager.RENTALS_TABLE, id);
    			  System.out.println(count);
    		   }
    		   else if(params[1].equals(type))
    		   {
    			   int count = TableManager.changeMailFlag(TableManager.RESERVES_TABLE, id);
     			  System.out.println(count);
    		   }
    	   }
        	
        	 dispatcher.forward(request, response);
        }
	}
	
	private class SMTPAuthenticator extends Authenticator 
	{
        private PasswordAuthentication authentication;

        public SMTPAuthenticator(String login, String password)
        {
            authentication = new PasswordAuthentication(login, password);
        }

        protected PasswordAuthentication getPasswordAuthentication()
        {
            return authentication;
        }
    }
}
